package com.yc.web.controller;

import com.yc.services.MyUserService;
import com.yc.web.DTO.MyUserDTO;
import com.yc.web.DTO.UpdatePasswordDTO;
import com.yc.web.controller.model.ResponseResult;
import jakarta.validation.Valid;
import lombok.extern.java.Log;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * 用户管理 REST API 控制器。
 */
@RestController
@RequestMapping("/users") // 所有用户管理相关的接口都以 /users 开头
@Log
public class MyUserController {

    private final MyUserService userService;

    public MyUserController(MyUserService userService) {
        this.userService = userService;
    }

    /**
     * 查询所有用户（仅限管理员）。
     * URL: GET /users
     * 权限：只有拥有 'ADMIN' 角色的用户才能访问。
     */
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<List<MyUserDTO>> getAllUsers() {
        List<MyUserDTO> users = userService.getAllUsers();
        return ResponseEntity.ok(users);
    }

    /**
     * 根据ID查询用户信息（管理员可以查询所有，普通用户只能查询自己）。
     * URL: GET /users/{id}
     * 权限：拥有 'ADMIN' 角色，或者请求的用户ID与路径中的ID一致。
     */
    @GetMapping("/{id}")
//    @PreAuthorize("hasRole('ADMIN') or #id == authentication.principal")
    @PreAuthorize("hasRole('ADMIN') or #id == T(java.lang.Long).parseLong(authentication.principal.toString())")
    public ResponseEntity<MyUserDTO> getUserById(@PathVariable Long id) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        log.info("===== DEBUG =====");
        log.info("Principal class: " + auth.getPrincipal().getClass().getName());
        log.info("Principal value: " + auth.getPrincipal());
        log.info("Authorities: " + auth.getAuthorities());
        log.info("===== END DEBUG =====");
        return userService.getUserById(id)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    /**
     * 更新用户信息（管理员可以更新所有，普通用户只能更新自己）。
     * URL: PUT /users/{id}
     * 权限：拥有 'ADMIN' 角色，或者请求的用户ID与路径中的ID一致。
     */
    @PutMapping("{userId}")
    @PreAuthorize("hasRole('ADMIN') or #userId == T(java.lang.Long).parseLong(authentication.principal.toString())")
    public ResponseEntity<ResponseResult> updateUser(@PathVariable("userId") Long userId, @Valid @RequestBody MyUserDTO userDTO) {
        // 获取当前认证用户的ID (从 Gateway 传递的 X-User-ID 头中获取)
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        log.info("[CONTROLLER] Principal: " + auth.getPrincipal());
        log.info("[CONTROLLER] Roles: " + auth.getAuthorities());

        String currentUserId = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

//        // 如果不是管理员且请求的ID不是当前用户ID，则拒绝访问
//        if (!SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream()
//                .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN")) && !currentUserId.equals(String.valueOf(userId))) {
//            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(ResponseResult.error("您没有权限更新该用户").setData("您没有权限更新该用户")); // 403 Forbidden
//        }

        try {
            MyUserDTO updatedUser = userService.updateUser(userId, userDTO);
            return ResponseEntity.ok(ResponseResult.ok("更新成功").setData(updatedUser));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(ResponseResult.error("更新失败").setData(e.getMessage())); // 400 Bad Request
        }
    }

    /**
     * 修改用户密码
     * URL: PUT /users/{userId}/password
     * 权限：用户只能修改自己的密码，管理员可以修改任意用户密码
     */
    @PutMapping("/{userId}/password")
    @PreAuthorize("hasRole('ADMIN') or #userId == T(java.lang.Long).parseLong(authentication.principal.toString())")
    public ResponseEntity<ResponseResult> updatePassword(
            @PathVariable Long userId,
            @Valid @RequestBody UpdatePasswordDTO updatePasswordDTO) {

        // 获取当前认证用户信息
//        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//        log.info("[Password Update] User ID: {}, Roles: {}", userId, auth.getAuthorities());

        try {
            // 调用服务层修改密码
            boolean isUpdated = userService.updateUserPassword(
                    userId,
                    updatePasswordDTO.getOldPassword(),
                    updatePasswordDTO.getNewPassword()
            );

            if (isUpdated) {
                return ResponseEntity.ok(ResponseResult.ok("密码修改成功"));
            } else {
                return ResponseEntity.badRequest().body(ResponseResult.error("密码修改失败"));
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(ResponseResult.error(e.getMessage()));
        } catch (Exception e) {
            log.info("密码修改异常"+ e.getMessage());
            return ResponseEntity.internalServerError().body(ResponseResult.error("系统异常"));
        }
    }

}